import React, { FC, useEffect, useMemo, useState } from 'react'
import { Button } from '@dandelion/mobile'
import { CheckList, Form, Input, Popup, SearchBar, Space, Toast } from 'antd-mobile'
import { format } from '@/utils/date'
import _ from 'lodash'
import { useAppSelector, useAppDispatch } from '@/store'
import {
  initProvince,
  setSubjectByProvince,
  subjectByProvince,
  setCurrentSubjectByProvinceParram,
  setDiagnosisParam,
  setLocalstorage,
  provinceList,
  diagnosisParam,
} from '@/store/fillLink'
import { getProvinceList, getSubjectByProvince, diagnosis } from '@/api/fillLink'

import { useNavigate } from 'react-router-dom'
import { ReqBaseInfo, Performance } from '@/types/fillLink'
const baseInfo: FC<{ setCurrent: React.Dispatch<React.SetStateAction<number>> }> = (props) => {
  const dispatch = useAppDispatch() //
  const navigate = useNavigate() //

  const diagnoParam = useAppSelector(diagnosisParam) || {}
  /**省份 */
  const provinceListtmp = useAppSelector(provinceList)
  /**科目 */
  const subjectByProvincetmp = useAppSelector(subjectByProvince)

  const [form] = Form.useForm<Partial<ReqBaseInfo>>()

  const provinclist = provinceListtmp.filter((val) => val.id === diagnoParam.province_id)
  const province_name = provinclist.length > 0 ? provinclist[0].name : ''

  const [formData, setFormData] = useState<Partial<ReqBaseInfo>>({
    ...diagnoParam,
    province_name: province_name,
  })
  useEffect(() => {
    form.setFieldsValue(formData)
  }, [])

  const [visible, setVisible] = useState(false)
  const [selected, setSelected] = useState(province_name)
  // const [searchText, setSearchText] = useState('')

  /**年份 */
  const timespanDate = +new Date(new Date().getFullYear() + '-06-08 23:59')
  const datalist = []
  if (Date.now() < timespanDate) {
    datalist.push(new Date().getFullYear().toString())
    datalist.push((new Date().getFullYear() + 1).toString())
    datalist.push((new Date().getFullYear() + 2).toString())
  } else {
    datalist.push((new Date().getFullYear() + 1).toString())
    datalist.push((new Date().getFullYear() + 2).toString())
    datalist.push((new Date().getFullYear() + 3).toString())
  }
  const yearListtmp: Array<string> = datalist
  const [visibleYearList, setYearListVisible] = useState(false)
  const [selectedYearList, setYearListSelected] = useState(
    diagnoParam && diagnoParam.year ? diagnoParam.year : '',
  )
  // const [searchTextYearList, setYearListSearchText] = useState('')

  /**关联学科科目 */
  const subjectProvince = async () => {
    const province_id = form.getFieldValue('province_id')
    const year = form.getFieldValue('year')
    if (province_id && year) {
      const res = await getSubjectByProvince({
        province_id: province_id,
        year: year,
      })
      dispatch(setSubjectByProvince(res.data))
    }
  }
  /**
   * 选中科目
   */
  const [subjectSelect, setSubjectSelect] = useState<Array<Performance>>(
    diagnoParam.performance || ([] as Array<Performance>),
  )

  useEffect(() => {
    dispatch(setDiagnosisParam({ performance: subjectSelect }))
  }, [subjectSelect])

  return (
    <div className="w-r35.1 h-auto bg-white text-r1.4  text-gray-333333  rounded-r0.8">
      <Form layout="horizontal" mode="card" form={form}>
        <Form.Header></Form.Header>
        <Form.Item
          className=" text-r1.4  text-gray-333333"
          label="学生姓名"
          name="stu_name"
          rules={[{ required: true }, { type: 'string', max: 10 }]}
        >
          <Input
            placeholder="请输入姓名"
            defaultValue={formData.stu_name}
            style={{ '--font-size': '1.4rem' }}
            className="text-gray-999999 "
          />
        </Form.Item>

        <Form.Item
          className=" text-r1.4  text-gray-333333"
          label="高考年份"
          name="year"
          rules={[{ required: true }]}
        >
          <div
            className="w-auto h-auto"
            onClick={() => {
              setYearListVisible(true)
            }}
          >
            <Input
              placeholder="请选择参加高考的年份"
              style={{ width: '21.0rem', '--font-size': '1.4rem' }}
              className="overflow-ellipsis w-r10.0 text-gray-999999 text-r1.4"
              readOnly
              defaultValue={formData.year?.toString()}
              value={selectedYearList.toString()}
            />
            <span className=" absolute z-10 right-r1.3 top-r1.5 bg-white">
              <i className="w-r2.0 h-r2.0 iconfont icon-icon_pulldown"></i>
            </span>
          </div>
        </Form.Item>

        <Form.Item
          className=" text-r1.4  text-gray-333333"
          label="所在省份"
          name="province_id"
          rules={[{ required: true }]}
        >
          <div
            className="w-auto h-auto"
            onClick={() => {
              setVisible(true)
            }}
          >
            <Input
              placeholder="选择所在地区"
              style={{ width: '21.0rem', '--font-size': '1.4rem' }}
              className="overflow-ellipsis w-r10.0  text-r1.4 text-gray-999999 "
              readOnly
              defaultValue={formData.province_name}
              value={selected}
            />
            <span className=" absolute z-10 right-r1.3 top-r1.5 bg-white">
              <i className="w-r2.0 h-r2.0 iconfont icon-icon_pulldown"></i>
            </span>
          </div>
        </Form.Item>
      </Form>
      {subjectByProvincetmp &&
      subjectByProvincetmp.subject &&
      subjectByProvincetmp.subject.length > 0 ? (
        <div className=" pb-r4.0">
          <div className=" m-r1.6">
            <div className=" relative w-r0.4 top-r0.2 h-r1.6 inline-block  bg-gradient-to-b from-orange-FF3627 to-orange-FF664F mr-r0.6 "></div>
            <span className=" text-gray-333333 text-r1.6">选择考试科目:</span>
          </div>
          <div>
            {subjectByProvincetmp.subject.map((node, key) => {
              return (
                <span
                  key={key}
                  onClick={() => {
                    const tmp = _.cloneDeep(subjectSelect)
                    if (tmp.filter((val) => val.id === node.id).length > 0) {
                      setSubjectSelect(
                        _.remove(tmp, (n) => {
                          return n.id === node.id
                        }),
                      )
                      return
                    }
                    let selectNum = 0
                    if (subjectByProvincetmp.subject!.length >= 3) {
                      selectNum = 3
                    } else {
                      selectNum = 1
                    }
                    if (tmp.length >= selectNum) {
                      tmp.shift()
                    }
                    tmp.push({
                      ...node,
                      amend_subject_score: 0,
                      score: 0,
                    })
                    setSubjectSelect(tmp)
                  }}
                  style={{
                    backgroundColor:
                      subjectSelect.filter((val) => val.id === node.id).length > 0
                        ? 'rgba(255,54,39,0.1)'
                        : '#F3F3F4',
                  }}
                  className={
                    ' w-r10.1 h-r4.0 text-r1.3 inline-block  rounded-r2.0 text-center  leading-r4.0 m-r0.7 cursor-pointer ' +
                    (subjectSelect.filter((val) => val.id === node.id).length > 0
                      ? ' text-orange-FF3627'
                      : ' bg-gray-F3F3F4 text-gray-333333')
                  }
                >
                  {node.name}
                </span>
              )
            })}
          </div>
        </div>
      ) : null}

      <Popup
        visible={visible}
        onMaskClick={() => {
          setVisible(false)
        }}
        bodyStyle={{ maxHeight: '40vh' }}
        destroyOnClose
      >
        <div>
          {/* <SearchBar
            placeholder="输入文字过滤选项"
            value={searchText}
            onChange={(v) => {
              setSearchText(v)
            }}
          /> */}
        </div>
        <div>
          <CheckList
            defaultValue={selected ? [selected] : []}
            onChange={(val) => {
              setSelected(val[0])
              form.setFieldValue(
                'province_id',
                provinceListtmp.filter((value) => value.name == val[0])[0].id,
              )
              form.setFieldValue(
                'province_name',
                provinceListtmp.filter((value) => value.name == val[0])[0].name,
              )
              /**获取省份数据 */
              subjectProvince()
              //province_name
              setVisible(false)
            }}
          >
            {provinceListtmp.map((item) => (
              <CheckList.Item key={item.id} value={item.name}>
                {item.name}
              </CheckList.Item>
            ))}
          </CheckList>
        </div>
      </Popup>
      <Popup
        visible={visibleYearList}
        onMaskClick={() => {
          setYearListVisible(false)
        }}
        bodyStyle={{ maxHeight: '40vh' }}
        destroyOnClose
      >
        <div>
          {/* <SearchBar
            placeholder="输入文字过滤选项"
            value={searchTextYearList}
            onChange={(v) => {
              setYearListSearchText(v)
            }}
          /> */}
        </div>
        <div>
          <CheckList
            defaultValue={selectedYearList ? [selectedYearList.toString()] : []}
            onChange={(val) => {
              setYearListSelected(val[0])
              form.setFieldValue('year', val[0])
              /**获取省份数据 */
              subjectProvince()
              setYearListVisible(false)
            }}
          >
            {yearListtmp.map((item) => (
              <CheckList.Item key={item} value={item}>
                {item}
              </CheckList.Item>
            ))}
          </CheckList>
        </div>
      </Popup>
      <span
        className=" w-r31.1 h-r4.4 leading-r4.4 absolute z-100 rounded-r2.0 text-r1.5 text-white cursor-pointer  bg-gradient-to-r from-orange-FF664F to-orange-FF3627 bottom-r4.3  inline-block text-center left-1/2 -translate-x-1/2 "
        onClick={() => {
          /**toast validate */
          //Toast
          const province_id = form.getFieldValue('province_id')
          const year = form.getFieldValue('year')
          const stu_name = form.getFieldValue('stu_name')
          //subjectSelect
          if (!stu_name) {
            Toast.show({
              content: '请填写姓名 ',
            })
            return
          }
          if (!year) {
            Toast.show({
              content: '请选择高考年份',
            })
            return
          }

          if (!province_id) {
            Toast.show({
              content: '请选择正确的省',
            })
            return
          }

          if (subjectSelect.length === 0) {
            Toast.show({
              content: '请选择科目',
            })
            return
          }
          /** */
          form.validateFields().then((res) => {
            dispatch(setDiagnosisParam({ ...res }))
            dispatch(setLocalstorage())
            props.setCurrent(1)
          })
        }}
      >
        下一步
      </span>
    </div>
  )
}

export default baseInfo
